package com.xiaohe66.web.application.im.convert;

import com.xiaohe66.web.application.im.bo.MessageAddBo;
import com.xiaohe66.web.application.im.result.MessageListUnreadDigestResult;
import com.xiaohe66.web.application.im.result.MessageResult;
import com.xiaohe66.web.domain.im.agg.ImUser;
import com.xiaohe66.web.domain.im.agg.Message;
import com.xiaohe66.web.domain.im.repository.ImUserRepository;
import com.xiaohe66.web.domain.im.repository.MessageRepository;
import com.xiaohe66.web.domain.im.value.MessageId;
import com.xiaohe66.web.domain.im.value.MessageUnread;
import com.xiaohe66.web.infrastructure.domain.adapter.im.MessageConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xiaohe
 * @since 2023.08.10 13:42
 */
@Mapper
@RequiredArgsConstructor
@Slf4j
public abstract class MessageBoConverter implements MessageConverter {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private ImUserRepository imUserRepository;

    public List<MessageListUnreadDigestResult> toUnreadResult(List<MessageUnread> messageUnreadList) {

        return messageUnreadList.stream()
                .map(this::toResult)
                .toList();

    }

    public MessageListUnreadDigestResult toResult(MessageUnread messageUnread) {

        if (messageUnread == null) {
            return null;
        }

        ImUser imUser = imUserRepository.getByCreateId(messageUnread.getCreateId());

        MessageListUnreadDigestResult result = new MessageListUnreadDigestResult();

        result.setAccountId(asLongValue(messageUnread.getCreateId()));
        result.setNickname(imUser == null ? "未知用户" : imUser.getNickname().getValue());
        result.setLastMessage(toResult(getMessage(messageUnread.getLastId())));
        result.setQty(asLongValue(messageUnread.getQty()));

        return result;
    }

    public Message getMessage(MessageId lastId) {
        return messageRepository.getById(lastId);
    }

    /*public ImUserNickname getNickname(AccountId createId) {
        ImUser imUser = imUserRepository.getByCreateId(createId);
        return imUser.getNickname();
    }*/

    public abstract MessageResult toResult(Message message);

    public abstract List<MessageResult> toResult(List<Message> list);

    @Mapping(target = "accountId", source = "bo.toId")
    @Mapping(target = "createId", source = "bo.sendId")
    public abstract Message newMessage(MessageAddBo bo, Long id);

}
